package org.cy.shixun.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.cy.shixun.common.CustoException;
import org.cy.shixun.dto.OrderDto;
import org.cy.shixun.entity.*;
import org.cy.shixun.mapper.CartMapper;
import org.cy.shixun.mapper.GoodsMapper;
import org.cy.shixun.mapper.GoodsSizeMapper;
import org.cy.shixun.mapper.OrderMapper;
import org.cy.shixun.service.OrderItemService;
import org.cy.shixun.service.OrderService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author TrainingL
 * @since 2023-06-29
 */
@Service

public class OrderServiceImpl extends ServiceImpl<OrderMapper, Orders> implements OrderService {
    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private CartMapper cartMapper;

    @Autowired
    private GoodsMapper goodsMapper;

    @Autowired
    private GoodsSizeMapper goodsSizeMapper;

    @Autowired
    private OrderItemService orderItemService;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Orders orderInsert(OrderDto orderDto, String account) {
        LambdaQueryWrapper<Cart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Cart::getAccount,account);
        List<Cart> carts = cartMapper.selectList(queryWrapper);

        Orders order = new Orders();
        order.setAccount(account);
        BeanUtils.copyProperties(orderDto, order);

        //插入到订单表
        orderMapper.insert(order);

        //查询购物车
        List<OrderItem> collect = carts.stream().map(item -> {
            OrderItem orderItem = new OrderItem();
            orderItem.setOrderId(order.getId());
            BeanUtils.copyProperties(item, orderItem);
            return orderItem;
        }).collect(Collectors.toList());
        //插入到订单详情表
        orderItemService.saveBatch(collect);

        //清空购物车
        cartMapper.delete(queryWrapper);
        return order;
    }

    /**
     * 对比购物车所有商品库存
     *
     * @param account 账户
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteGoods(String account){
        LambdaQueryWrapper<Cart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Cart::getAccount,account);
        List<Cart> carts = cartMapper.selectList(queryWrapper);
        if(carts.size()<=0){
            throw new CustoException("物品为空");
        }
        //对比购物车中商品想要的数量和实际库存
        carts.forEach(cart->{
            int id=cart.getGoodsId();
            Goods goods = goodsMapper.selectById(id);

            int i = goods.getGoodsStorage() - cart.getWantedNum();
            if(i<0){
                cartMapper.deleteById(cart.getId());
                throw new CustoException("库存不足");
            }
            if(i==0){
                goodsMapper.deleteById(id);
                HashMap<String, Object> map = new HashMap<>();
                map.put("goods_id",id);
                goodsSizeMapper.deleteByMap(map);
            }else{
                goods.setGoodsStorage(i);
                goodsMapper.updateById(goods);
            }
        });
    }


    @Override
    @Transactional(rollbackFor = Exception.class,noRollbackFor = CustoException.class)
    public Orders buy(OrderDto orderDto, String account) {
        //查询商品库存
        Goods goods = goodsMapper.selectById(orderDto.getGoodsId());
        Integer goodsStorage = goods.getGoodsStorage();
        int num=goodsStorage-orderDto.getGoodsNum();
        if(num<0){
            throw new CustoException("库存不足");
        }

        LambdaQueryWrapper<GoodsSize> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(GoodsSize::getGoodsId,orderDto.getGoodsId());
        //如果库存为0，则删除商品
        if(num==0){
            goodsMapper.deleteById(orderDto.getGoodsId());
            goodsSizeMapper.delete(queryWrapper);
        }
        else {
            //否则更新商品表
            goods.setGoodsStorage(num);
            goodsMapper.updateById(goods);
        }
            Orders orders = new Orders();
            orders.setAccount(account);
            BeanUtils.copyProperties(orderDto,orders);
            //插入订单表
            orderMapper.insert(orders);

            OrderItem orderItem = new OrderItem();
            orderItem.setOrderId(orders.getId());
            orderItem.setGoodsId(orderDto.getGoodsId());
            orderItem.setAccount(account);
            orderItem.setGoodsName(goods.getGoodsName());
            orderItem.setWantedNum(orderDto.getGoodsNum());
            orderItem.setGoodsMoney(orderDto.getPrice());
            orderItem.setGoodsSize(orderDto.getSize());
            //插入订单详情表
            orderItemService.save(orderItem);
        return orders;


    }
}
